import {observable, extendObservable, action, toJS} from 'mobx';
import {recoveryCardInfo} from 'util/api';
import _ from 'lodash';
import {validateFields, getParams} from '../Common.js';
import {message} from 'antd';

//导出
export default class AddUnit {
  constructor() {
    this.reset(true);
    this.mediaStreamTrack = null;
  }

  @action
  reset = init => {
    const state = {
      type: 'new',
      fields: {
        cardNumber: {
          value: '',
          require: false,
        },
        reason: {value: '', require: false},
        blockAndUnit: {value: '', require: false},
        cname: {value: '', require: false},
      },

      currentData: {},
    };

    if (init) {
      extendObservable(this, state);
    } else {
      Object.keys(state).forEach(key => (this[key] = state[key]));
    }
  };

  //取消新增单元
  @action
  resetFields = async () => {
    this.fields = {
      cardNumber: {
        value: '',
        require: false,
      },
      reason: {value: '', require: false},
      blockAndUnit: {value: '', require: false},
      cname: {value: '', require: false},
    };
  };

  @action
  onRestore = async (record, store) => {
    //清空fields
    this.resetFields();
    this.currentData = record;
    let obj = toJS(this.fields);
    obj['cname'].value = record.name || '';
    obj['cardNumber'].value = record.cardNumber || '';
    obj['blockAndUnit'].value = record.blockAndUnit || '';
    obj['reason'].value = record.reason || '';
    this.fields = obj;
    store.confim('restore');
  };
  @action
  restoreOk = async (cancle, store) => {
    //校验字段
    validateFields(
      toJS(this.fields),
      async fields => {
        let params = getParams(fields);
        delete params['cname'];
        delete params['blockAndUnit'];
        delete params['reason'];
        params['cardId'] = this.currentData['cardId'];

        let res = await recoveryCardInfo(params);
        if (res.result === 'success') {
          cancle();
          message.success(res.msg);
          store.getCardInfo();
        } else {
          message.error(res.msg);
        }
      },
      newFields => {
        this.fields = newFields;
      },
    );
  };
  //改变字段
  @action
  handleFormChange = async changedFields => {
    const key = _.keys(changedFields);
    //showError让自己校验字段;
    const obj = {};
    obj[key] = {showError: false, ...changedFields[key]};
    this.fields = {...toJS(this.fields), ...obj};
  };
}
